import React, { useState, useContext } from 'react';
import { UserContext } from '../contexts/UserContext';
import './LocationTester.css';

// 坐标转换函数：GCJ02 转 WGS84
const transformFromGCJToWGS = (gcjLat, gcjLon) => {
  const pi = 3.14159265358979324;
  const a = 6378245.0;
  const ee = 0.00669342162296594323;

  if (outOfChina(gcjLat, gcjLon)) {
    return { latitude: gcjLat, longitude: gcjLon };
  }

  let dLat = transformLat(gcjLon - 105.0, gcjLat - 35.0);
  let dLon = transformLon(gcjLon - 105.0, gcjLat - 35.0);
  const radLat = gcjLat / 180.0 * pi;
  let magic = Math.sin(radLat);
  magic = 1 - ee * magic * magic;
  const sqrtMagic = Math.sqrt(magic);
  dLat = (dLat * 180.0) / ((a * (1 - ee)) / (magic * sqrtMagic) * pi);
  dLon = (dLon * 180.0) / (a / sqrtMagic * Math.cos(radLat) * pi);
  
  const wgsLat = gcjLat - dLat;
  const wgsLon = gcjLon - dLon;

  return { latitude: wgsLat, longitude: wgsLon };
};

// 坐标转换函数：WGS84 转 GCJ02
const transformFromWGSToGCJ = (wgsLat, wgsLon) => {
  const pi = 3.14159265358979324;
  const a = 6378245.0;
  const ee = 0.00669342162296594323;

  if (outOfChina(wgsLat, wgsLon)) {
    return { latitude: wgsLat, longitude: wgsLon };
  }

  let dLat = transformLat(wgsLon - 105.0, wgsLat - 35.0);
  let dLon = transformLon(wgsLon - 105.0, wgsLat - 35.0);
  const radLat = wgsLat / 180.0 * pi;
  let magic = Math.sin(radLat);
  magic = 1 - ee * magic * magic;
  const sqrtMagic = Math.sqrt(magic);
  dLat = (dLat * 180.0) / ((a * (1 - ee)) / (magic * sqrtMagic) * pi);
  dLon = (dLon * 180.0) / (a / sqrtMagic * Math.cos(radLat) * pi);
  
  const gcjLat = wgsLat + dLat;
  const gcjLon = wgsLon + dLon;

  return { latitude: gcjLat, longitude: gcjLon };
};

// 判断是否在中国境外
const outOfChina = (lat, lon) => {
  if (lon < 72.004 || lon > 137.8347) {
    return true;
  }
  if (lat < 0.8293 || lat > 55.8271) {
    return true;
  }
  return false;
};

// 转换纬度
const transformLat = (x, y) => {
  let ret = -100.0 + 2.0 * x + 3.0 * y + 0.2 * y * y + 0.1 * x * y + 0.2 * Math.sqrt(Math.abs(x));
  ret += (20.0 * Math.sin(6.0 * x * Math.PI) + 20.0 * Math.sin(2.0 * x * Math.PI)) * 2.0 / 3.0;
  ret += (20.0 * Math.sin(y * Math.PI) + 40.0 * Math.sin(y / 3.0 * Math.PI)) * 2.0 / 3.0;
  ret += (160.0 * Math.sin(y / 12.0 * Math.PI) + 320 * Math.sin(y * Math.PI / 30.0)) * 2.0 / 3.0;
  return ret;
};

// 转换经度
const transformLon = (x, y) => {
  let ret = 300.0 + x + 2.0 * y + 0.1 * x * x + 0.1 * x * y + 0.1 * Math.sqrt(Math.abs(x));
  ret += (20.0 * Math.sin(6.0 * x * Math.PI) + 20.0 * Math.sin(2.0 * x * Math.PI)) * 2.0 / 3.0;
  ret += (20.0 * Math.sin(x * Math.PI) + 40.0 * Math.sin(x / 3.0 * Math.PI)) * 2.0 / 3.0;
  ret += (150.0 * Math.sin(x / 12.0 * Math.PI) + 300.0 * Math.sin(x / 30.0 * Math.PI)) * 2.0 / 3.0;
  return ret;
};

const LocationTester = () => {
  const { username } = useContext(UserContext);
  const [longitude, setLongitude] = useState('116.397428');  // 天安门经度
  const [latitude, setLatitude] = useState('39.90923');      // 天安门纬度
  const [message, setMessage] = useState('');
  const [error, setError] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const [isExpanded, setIsExpanded] = useState(false);
  const [coordType, setCoordType] = useState('gcj02'); // 默认为高德坐标系(GCJ02)

  // 预设位置
  const presetLocations = [
    { name: '天安门', longitude: '116.397428', latitude: '39.90923', type: 'gcj02' },
    { name: '上海东方明珠', longitude: '121.4952', latitude: '31.2396', type: 'gcj02' },
    { name: '西安钟楼', longitude: '108.9402', latitude: '34.2596', type: 'gcj02' },
    { name: '广州塔', longitude: '113.3187', latitude: '23.1066', type: 'gcj02' }
  ];

  const handleSubmit = async (e) => {
    e.preventDefault();
    setIsLoading(true);
    setMessage('');
    setError('');

    try {
      // 将坐标转换为WGS84格式
      const lng = parseFloat(longitude);
      const lat = parseFloat(latitude);
      
      if (isNaN(lng) || isNaN(lat)) {
        throw new Error('坐标格式不正确，请输入有效的数字');
      }
      
      // 根据选择的坐标系进行转换
      let wgsCoords;
      if (coordType === 'gcj02') {
        // 从GCJ02(高德)转换到WGS84
        wgsCoords = transformFromGCJToWGS(lat, lng);
        console.log('坐标转换: GCJ02 -> WGS84', { 
          原始坐标: { latitude: lat, longitude: lng },
          转换后: wgsCoords 
        });
      } else if (coordType === 'wgs84') {
        // 已经是WGS84，不需要转换
        wgsCoords = { latitude: lat, longitude: lng };
        console.log('使用原始WGS84坐标', wgsCoords);
      } else {
        throw new Error('不支持的坐标系类型');
      }

      console.log('发送测试坐标:', {
        username,
        原始坐标: { longitude: lng, latitude: lat, 类型: coordType },
        发送坐标: { longitude: wgsCoords.longitude, latitude: wgsCoords.latitude, 类型: 'WGS84' }
      });

      const response = await fetch('/api/test/location', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          username,
          longitude: wgsCoords.longitude,
          latitude: wgsCoords.latitude,
        }),
      });

      const data = await response.json();

      if (!response.ok) {
        throw new Error(data.error || '发送坐标失败');
      }

      setMessage(`${data.message} (已自动将${coordType === 'gcj02' ? '高德' : 'GPS'}坐标转换为WGS84格式)`);
      console.log('坐标发送成功:', data);
    } catch (err) {
      console.error('发送坐标失败:', err);
      setError(err.message);
    } finally {
      setIsLoading(false);
    }
  };
  
  const selectPresetLocation = (preset) => {
    setLongitude(preset.longitude);
    setLatitude(preset.latitude);
    setCoordType(preset.type || 'gcj02');
  };

  return (
    <div className={`location-tester ${isExpanded ? 'expanded' : 'collapsed'}`}>
      <div className="tester-header" onClick={() => setIsExpanded(!isExpanded)}>
        <h2>坐标测试工具</h2>
        <span className="toggle-icon">{isExpanded ? '▼' : '▶'}</span>
      </div>
      
      {isExpanded && (
        <div className="tester-content">
          <div className="preset-locations">
            <h3>预设位置</h3>
            <div className="preset-buttons">
              {presetLocations.map((preset, index) => (
                <button 
                  key={index} 
                  type="button" 
                  className="preset-button"
                  onClick={() => selectPresetLocation(preset)}
                >
                  {preset.name}
                </button>
              ))}
            </div>
          </div>
          
      <form onSubmit={handleSubmit}>
            <div className="coord-type-selector">
              <label>坐标系类型:</label>
              <div className="radio-group">
                <label className="radio-label">
                  <input
                    type="radio"
                    name="coordType"
                    value="gcj02"
                    checked={coordType === 'gcj02'}
                    onChange={() => setCoordType('gcj02')}
                  />
                  <span>高德坐标系 (GCJ02)</span>
                </label>
                <label className="radio-label">
                  <input
                    type="radio"
                    name="coordType"
                    value="wgs84"
                    checked={coordType === 'wgs84'}
                    onChange={() => setCoordType('wgs84')}
                  />
                  <span>GPS原始坐标 (WGS84)</span>
                </label>
              </div>
            </div>
            
            <div className="input-container">
        <div className="input-group">
          <label htmlFor="longitude">经度:</label>
          <input
            type="text"
            id="longitude"
            value={longitude}
            onChange={(e) => setLongitude(e.target.value)}
            placeholder="输入经度 (-180 到 180)"
            required
          />
        </div>
        <div className="input-group">
          <label htmlFor="latitude">纬度:</label>
          <input
            type="text"
            id="latitude"
            value={latitude}
            onChange={(e) => setLatitude(e.target.value)}
            placeholder="输入纬度 (-90 到 90)"
            required
          />
        </div>
            </div>
            
        <button 
          type="submit" 
          className="submit-button"
          disabled={isLoading || !username}
        >
              {isLoading ? (
                <>
                  <span className="loading-spinner"></span>
                  发送中...
                </>
              ) : (
                <>
                  <i className="icon-send"></i>
                  发送坐标
                </>
              )}
        </button>
      </form>
          
      {message && <div className="success-message">{message}</div>}
      {error && <div className="error-message">{error}</div>}
      {!username && <div className="warning-message">请先登录后再测试坐标</div>}
          
          <div className="tester-help">
            <p>
              <i className="icon-info"></i>
              此工具会自动将您输入的坐标转换为WGS84格式后发送
            </p>
            <div className="coord-info">
              <p><strong>高德坐标系 (GCJ02)</strong>: 高德地图、腾讯地图使用的坐标系</p>
              <p><strong>GPS原始坐标 (WGS84)</strong>: GPS设备获取的原始坐标</p>
            </div>
            
            <div className="data-format-example">
              <h4>数据发送格式示例</h4>
              <div className="format-box">
                <code>{username}|{longitude},{latitude}</code>
                <p className="format-description">例如: <code>user123|116.397428,39.90923</code></p>
                <p className="format-note">注意: 系统会自动将坐标转换为WGS84格式后存储，您无需手动转换</p>
              </div>
              <p className="tcp-hint">如需通过TCP客户端发送数据，请使用上述格式</p>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default LocationTester; 